package com.eeds.interceptor;

import com.eeds.common.enums.DeviceType;
import com.eeds.common.enums.LanguageType;
import com.eeds.common.enums.LoginType;
import com.eeds.common.table.UserRoleAssEntity;
import com.eeds.exception.AuthException;
import com.eeds.common.model.RespEnum;
import com.eeds.exception.ServerException;
import com.eeds.common.constant.ParametersConstants;
import com.eeds.common.constant.RedisConstant;
import com.eeds.json.GsonUtil;
import com.eeds.para.ParametersUtil;
import com.eeds.redis.StringRedisUtil;
import com.eeds.servlet.HttpServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 拦截器的编写
 * @author sunjg
 */
@Slf4j
@Configuration
public class AuthInterceptor extends HandlerInterceptorAdapter {

   @Autowired
   private StringRedisUtil redisUtil;


    /**
     * 对于含有 AuthValidation标签的Controller方法，验证请求里的token和userId。
     * 对于不含 AuthValidation标签的Controller方法，直接放行。
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpServletUtil.init(request,response);

        if(request.getMethod().equals("OPTIONS")){
            return true;
        }





        HandlerMethod m = (HandlerMethod) handler;
        NeedAuth needAuth = m.getMethod().getAnnotation(NeedAuth.class);

        String uri = request.getServletPath();
        if(uri.indexOf("/pc/upload/uploadFile") > -1){//过滤图片上传
            return true;
        }
        if(uri.indexOf("/pc/fileCabinet/getFileList") > -1){//过滤图片上传
            return true;
        }
        if (needAuth == null) {
            return true;
        }
        String token = request.getHeader(ParametersConstants.ACCESS_TOKEN);
        if(token == null){
            throw new ServerException(RespEnum.USER_AUTHENTICATION);
        }



        String userId = redisUtil.get(RedisConstant.USER_ACCESS_TOKEN+token);
        if(userId != null && userId.length()>0){
            if(log.isInfoEnabled()){
                log.info("[head]-->Token:{}",token);
            }
            request.setAttribute(ParametersConstants.USER_ID,userId);
            if(needAuth.role() == 1){
                String userRoleAssListJson = redisUtil.get(RedisConstant.USER_ACCESS_ROLE +  userId);
                if(userRoleAssListJson != null){
                    List<UserRoleAssEntity> userRoleAssList = GsonUtil.jsonToList(userRoleAssListJson, UserRoleAssEntity.class);
                    Boolean falg = false;
                    for (UserRoleAssEntity userRoleAssEntity : userRoleAssList) {
                        if(userRoleAssEntity.getIdxUserRole() == 1L){
                            falg = true;
                        }
                    }
                    if(!falg) {
                        throw new AuthException(RespEnum.USER_AUTHENTICATION);
                    }

                }else {
                    throw new AuthException(RespEnum.USER_AUTHENTICATION);
                }
            }
            return true;
        }else {
            throw new AuthException(RespEnum.USER_AUTHENTICATION);
        }


    }





    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if(log.isInfoEnabled()) {
            log.info("SYS_INFO time:{}|ip:{}|uri:{}|agent:{}",
                    new Object[]{
                            (System.currentTimeMillis() - (Long) request.getAttribute("AUTH_START_TIME")),
                            request.getRequestURI(),
                            request.getHeader("User-agent")
                    }
            );
        }

    }


}
